package com.gdones.gateway.config;

import com.alibaba.fastjson.JSON;
import com.gdones.common.core.dto.MyResult;
import com.gdones.common.core.util.MyJWTUtil;
import com.gdones.gateway.dto.NotAuthUrlProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * Token验证filter
 * 2023/4/27
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    @Autowired
    private NotAuthUrlProperties notAuthUrlProperties;

    /**
     * 过滤器方法
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String currentUrl = exchange.getRequest().getURI().getPath();
        log.info("-token拦截器拦截:"+currentUrl);

        //1:不需要认证的url,不过滤放行的url
        if (shouldSkip(currentUrl)) {
            log.info("==========已跳过url{}=====", currentUrl);
            return chain.filter(exchange);
        }

        // 从请求头中获取token
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst("token");

        if(token==null||token==""){// token为空
            MyResult errRes = new MyResult("-1","认证失败，token不存在！");
            String jsonString = JSON.toJSONString(errRes);
            response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
            response.setStatusCode(HttpStatus.OK);
            return response.writeWith(Mono.just(response.bufferFactory().wrap(jsonString.getBytes())));
        }else{ // 有值

            boolean verify = MyJWTUtil.verify(token);

            if(verify){
                // 放行
                return chain.filter(exchange);
            }else{
                MyResult errRes = new MyResult("-1","认证失败，token失效！");
                String jsonString = JSON.toJSONString(errRes);
                response.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                response.setStatusCode(HttpStatus.OK);
                return response.writeWith(Mono.just(response.bufferFactory().wrap(jsonString.getBytes())));
            }
        }
    }

    /**
     * 过滤器排序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 方法实现说明:不需要过滤的路径
     * <p>
     * //     * @param currentUrl 当前请求路径
     */
    private boolean shouldSkip(String currentUrl) {
        for (String skipPath : notAuthUrlProperties.getTokenFilterShouldSkipUrls()) {

            boolean b = currentUrl.indexOf(skipPath) != -1;

            if(b){
                return true;
            }
        }
        return false;
    }

}
